﻿#include "http_rep.h"

json_rep str_to_json_object(std::string_view req_body, json::object& obj) {
    json::error_code ec;
    json::value      v = json::parse(req_body, ec);

    if (ec)
        return HTTP_NOT_JSON(req_body);

    if (!v.is_object())
        return HTTP_NOT_JSON_OBJ(req_body);

    obj = v.as_object();

    return HTTP_SUCCESS;
}


// 在JSON对象中，查找指定的参数（std::string)
json_rep get_string(json::object& obj, std::string_view param_name, std::string& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_string())
        return HTTP_FIELD_TYPE_ERR(param_name, "string");

    param = v->as_string();

    return HTTP_SUCCESS;
}

// 在JSON对象中，查找指定的参数（int int64）
json_rep get_int(json::object& obj, std::string_view param_name, int& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_int64())
        return HTTP_FIELD_TYPE_ERR(param_name, "int");

    param = (int)v->as_int64();

    return HTTP_SUCCESS;
}

// 在JSON对象中，查找指定的参数（uint64_t）
json_rep get_uint(json::object& obj, std::string_view param_name, uint64_t& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_uint64())
        return HTTP_FIELD_TYPE_ERR(param_name, "uint");

    param = v->as_uint64();

    return HTTP_SUCCESS;
}

// 在JSON对象中，查找指定的参数（double）
json_rep get_double(json::object& obj, std::string_view param_name, double& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_double())
        return HTTP_FIELD_TYPE_ERR(param_name, "double");

    param = v->as_double();

    return HTTP_SUCCESS;
}

// 在JSON对象中，查找指定的参数（bool）
json_rep get_bool(json::object& obj, std::string_view param_name, bool& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_bool())
        return HTTP_FIELD_TYPE_ERR(param_name, "bool");

    param = v->as_bool();

    return HTTP_SUCCESS;
}

json_rep get_object(json::object& obj, std::string_view param_name, json::object& param) {
    const json::value* v = obj.if_contains(param_name);

    if (nullptr == v)
        return HTTP_FIELD_NOT_FOUND(param_name);

    if (!v->is_object())
        return HTTP_FIELD_TYPE_ERR(param_name, "object");

    param = v->as_object();

    return HTTP_SUCCESS;
}